<template>
	<view class="page">
		<!-- <view class="system-height" :style="{height:statusBarHeight}"></view> -->
		<!-- #ifdef MP -->
<!-- 		<view class="title-bar" style="height: 43px;">
			<view class="icon" @click="back" v-if="!isHome">
				<image src="../static/left.png"></image>
			</view>
			<view class="icon" @click="home" v-else>
				<image src="../static/home.png"></image>
			</view>
			账户登录
		</view> -->
		<!-- #endif -->
		<view class="wechat_login">
			<view class="img">
				<image :src="adminUrl+'/upload/goulogo.png'" mode="widthFix"></image>
			</view>
			<view class="btn-wrapper">
				<!-- #ifdef H5 -->
				<button hover-class="none" @click="wechatLogin" class="bg-color btn1">手机号快捷登录</button>
				<!-- #endif -->
				<!-- #ifdef MP -->
				<button hover-class="none" @tap="getUserProfile" class="bg-color btn1">手机号快捷登录</button>
				<!-- #endif -->
				<!-- <button hover-class="none" @click="isUp = true" class="btn2">手机号登录</button> -->
			</view>
			<div class="protocol acea-row row-top">
				<checkbox-group class="checkgroup acea-row" @change='changeCheck'>
					<label>
						<checkbox :checked = 'isAgree' color="#C31026" style="border-radius: 50%;transform:scale(0.7)"/>
					</label>
				</checkbox-group>
				<view class="protocol_text size14">
					登录即代表同意<text @click="userAgree" class="font_pro">《隐私协议》</text>并授权使用您的账号信息（如昵称、 头像、地址等信息）以便您统一管理
				</view>
			</div>
		</view>		
		<atModel v-if="isPhoneBox" 
		:userPhoneType="true" 
		:isPhoneBox="isPhoneBox"  
		:authKey="authKey" 
		:content="getPhoneContent"
		:userId="uid"
		 @closeModel="bindPhoneClose" 
		 @confirmModel="confirmModel"></atModel>
	</view>
</template>

<script>
	const app = getApp();
	let statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
	import atModel from '@/components/model/index.vue'
	import {mapGetters} from "vuex";
	import {getUserPhone, getUserMeg} from '@/api/login';
	import {
		LOGO_URL,
		EXPIRES_TIME,
		USER_INFO,
		STATE_R_KEY
	} from '@/config/cache';
	import {getUserInfo} from '@/api/user'
	import Empower from '@/libs/empower';
	import wechat from "@/libs/authWechat";
	import store from "@/store";
	import { openPamperSubscribe } from '@/utils/SubscribeMessage.js'
	export default {
		data() {
			return {
				adminUrl:this.$config.Http_admin_url,
				isUp: false,
				isAgree:false,
				phone: '',
				statusBarHeight: statusBarHeight,
				isHome: false,
				isPhoneBox: false,
				logoUrl: '',
				code: '',
				authKey: '',
				options: '',
				userInfo: {},
				codeNum: 0,
				theme:app.globalData.theme,
				getPhoneContent:'申请获取您的手机号用于注册，完成后可使用系统更多功能'
			}
		},
		components: {
			atModel
		},
		computed: mapGetters(['uid']),
		onLoad(options) {
			let that = this
			// #ifdef H5
			document.body.addEventListener("focusout", () => {
				setTimeout(() => {
					const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop ||
						0;
					window.scrollTo(0, Math.max(scrollHeight - 1, 0));
				}, 100);
			});
			const {
				code,
				state,
				scope
			} = options;
			this.options = options
			// 获取确认授权code
			this.code = code || ''
			//if(!code) location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
			if (code && this.options.scope !== 'snsapi_base') {
				let spread = app.globalData.spread ? app.globalData.spread : 0;
				//公众号授权登录回调 wechatAuth(code, Cache.get("spread"), loginType)
				wechat.auth(code, spread).then(res => {
					if (res.type === 'login') {
						this.$store.commit('LOGIN', {
							token: res.token
						});
						this.$store.commit("SETUID", res.uid);
						if (res.type === 'register') {
							this.authKey = res.key;
							this.isUp = true
						}
						this.getUserInfo();
						//this.wechatPhone();
						//location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
					}
				}).catch(error => {});
			}
			// #endif
			let pages = getCurrentPages();
			// let prePage = pages[pages.length - 2];
			// if (prePage.route == 'pages/order_addcart/order_addcart') {
			// 	this.isHome = true
			// } else {
			// 	this.isHome = false
			// }

		},
		methods: {
			changeCheck(){
				this.isAgree = !this.isAgree; 
				this.$set(this,'isAgree', this.isAgree)
				// console.log("isAgree",this.isAgree)
			},
			userAgree(){
				uni.navigateTo({
					url:'/pages/about/index?id=7'
				})
			},
			back() {
				uni.navigateBack();
			},
			home() {
				uni.switchTab({
					url: '/pages/main/index/index'
				})
			},
			modelCancel(){
				this.isPhoneBox = false;
			},
			// 弹窗关闭
			maskClose() {
				// this.isUp = false  //点击模态框会关闭登录弹框，防止用户误触而关闭
			},
			bindPhoneClose(data) {
				if (data.isStatus) {
					this.isPhoneBox = false
					this.$base.Tips({
						title: '登录成功',
						icon: 'success'
					}, {
						tab: 3
					})
				} else {
					this.isPhoneBox = false
				}
			},
			// #ifdef MP
			/**
			 * 获取订阅信息权限
			**/ 
			openSubscribes(){
				openPamperSubscribe().then((res)=>{
					console.log('Subscribe',res)
				})
			},
			
			/**
			 * 获取个人用户信息
			 */
			getUserInfo: function() {
				let that = this;
				let param={
					userid:this.uid,
					token:store.state.app.token
				}
				// console.log('param',param)
				getUserInfo(param).then(res => {
					// console.log('getUserInfo',res)
					uni.hideLoading();
					that.userInfo = res.data
					that.$store.commit("UPDATE_USERINFO", res.data);
					if(that.userInfo.tel == '' || that.userInfo.tel == null){
					  return that.isPhoneBox = true
					}
					that.$base.Tips({
						title: '登录成功',
						icon: 'success'
					}, {
						tab: 3
					})
				});
			},
			getUserProfile() {
				let self = this;
				if(!self.isAgree) return self.$base.Tips({
					title:'请先阅读《隐私协议》，并勾选'
				})
				uni.showLoading({
					title: '正在登录中'
				});
				Empower.getUserProfile().then(res => {
					console.log('UserProfile',res)
					Empower.getCode()
						.then(code => {
							uni.setStorageSync('code',code)
							// console.log('getCode',code)
							self.getWxUser(code, res);							
						})
						.catch(res => {
							uni.hideLoading();
						});
				})
				.catch(res => {
					uni.hideLoading();
				});
			},

			getWxUser(code, res) {
				let self = this
				let spread = Number(uni.getStorageSync('spread'))
				let userInfo = res.userInfo;
				userInfo.code = code;
				userInfo.spread_spid = spread ? spread : 0; //获取推广人ID
				userInfo.avatar = userInfo.userInfo.avatarUrl;
				userInfo.city = userInfo.userInfo.city;
				userInfo.country = userInfo.userInfo.country;
				userInfo.nickName = userInfo.userInfo.nickName;
				userInfo.province = userInfo.userInfo.province;
				userInfo.sex = userInfo.userInfo.gender;
				userInfo.type = 'routine'
				// self.$base.Tips({
				// 	title:'spread_spid:'+userInfo.spread_spid
				// })
				Empower.authUserInfo(userInfo.code, userInfo).then(res => {
						console.log('authUserInfo',res)
						self.authKey = res.key;
						self.$store.commit('LOGIN', {
							token: res.token
						});
						self.$store.commit("SETUID", res.user_id);						
						if (res.user_one === 1) {
							uni.hideLoading();
							self.isPhoneBox = true
						}
						if (res.user_one === 2) {
							uni.hideLoading();
							self.getUserInfo();
						}
					})
					.catch(res => {
						uni.hideLoading();
						uni.showToast({
							title: res,
							icon: 'none',
							duration: 2000
						});
					});
			},
			// #endif
			// #ifdef H5
			// 获取url后面的参数
			getQueryString(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
				var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
				var r = window.location.search.substr(1).match(reg);
				var q = window.location.pathname.substr(1).match(reg_rewrite);
				if (r != null) {
					return unescape(r[2]);
				} else if (q != null) {
					return unescape(q[2]);
				} else {
					return null;
				}
			},
			// 公众号登录
			wechatLogin() {
				if(!this.isAgree) return this.$base.Tips({
					title:'请先阅读《隐私协议》，并勾选'
				})
				if (!this.code && this.options.scope !== 'snsapi_base') {
					this.$wechat.oAuth('snsapi_userinfo', '/pages/user/wechat_login/index');
				} else {
					// if (this.authKey) {
					// 	this.isUp = true;
					// }
					this.isUp = true;
				}
			},
			// 输入手机号后的回调
			wechatPhone() {
				this.$Cache.clear('snsapiKey');
				if (this.options.back_url) {
					let url = uni.getStorageSync('snRouter');
					url = url.indexOf('/pages/main/index/index') != -1 ? '/' : url;
					if (url.indexOf('/pages/user/wechat_login/index') !== -1) {
						url = '/';
					}
					if (!url) {
						url = '/pages/main/index/index';
					}
					this.isUp = false
					uni.showToast({
						title: '登录成功3',
						icon: 'none'
					})
					setTimeout(res => {
						location.href = url
					}, 800)
				} else {
					uni.navigateBack()
				}
			}
			// #endif
		}
	}
</script>

<style lang="scss">
	page {
		// background: #fff;
		height: 100%;
	}
    
	.page {
		background: #fff;
		height: 100%;
	}

	.wechat_login {
		padding: 72rpx 34rpx;
		text-align: center;
		.img{
			margin: 120rpx auto 0 auto;
		}
		.img image {
			width: 346rpx;
			height: 312rpx;
			border-radius: 50%;
		}

		.btn-wrapper {
			margin-top: 86rpx;
			padding: 0 25rpx;

			button {
				width: 100%;
				height: 86rpx;
				line-height: 86rpx;
				margin-bottom: 40rpx;
				border-radius: 46rpx;
				font-size: 30rpx;
				&.btn1 {
					color: #fff;
				}

				&.btn2 {
					color: #666666;
					border: 1px solid #666666;
				}
			}  
		}
		.protocol {
			margin-top: 20rpx;
			.protocol_text {
				width: 90%;
				text-align: left;
				.font_pro {
					color: #518BFF;
				}
			}
			/deep/uni-checkbox .uni-checkbox-input{
				border-radius: 50% !important;
			}
			/deep/uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked:before{
				font-size: 36rpx !important;
			}
		}
	}

	.title-bar {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
	}

	.icon {
		position: absolute;
		left: 30rpx;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 86rpx;
		height: 86rpx;

		image {
			width: 50rpx;
			height: 50rpx;
		}
	}
	
	.bg-color{
		background-color: #C31026 !important;
		// @include main_bg_color(theme)
	}
</style>
